#pragma once

#include <iostream>
#include <memory>
#include <sys/epoll.h>
#include "Socket.hpp"
#include "Epoller.hpp"
#include "Log.hpp"
#include "nocopy.hpp"

uint32_t ET_EVENT_IN = (EPOLLIN);
uint32_t ET_EVENT_OUT = (EPOLLOUT);

// 此程序的read/write仍忽略了网络读取报文完整性问题 主要考虑epoll逻辑
class EpollServer : public nocopy
{
    static const int num = 64;

private:
    std::shared_ptr<Epoller> _epollerPtr;

    std::shared_ptr<Sock> _listenSocketPtr;
    uint16_t _port;

public:
    EpollServer(uint16_t port)
        : _port(port),
          _listenSocketPtr(new Sock()),
          _epollerPtr(new Epoller())
    {
    }

    void Init()
    {
        _listenSocketPtr->Socket();
        _listenSocketPtr->Bind(_port);
        _listenSocketPtr->Listen();

        lg(Info, "create listen socket success: %d\n", _listenSocketPtr->getSocketFd());
    }

    void Accepter() // 获取了一个新连接
    {
        std::string clientip;
        uint16_t clientport;
        int sock = _listenSocketPtr->Accept(&clientip, &clientport);
        if (sock > 0)
        {
            // 不能直接读取 原因select/poll已讲
            _epollerPtr->EpllerUpdate(EPOLL_CTL_ADD, sock, ET_EVENT_IN);
            lg(Info, "get a new link, client info@ %s:%d", clientip.c_str(), clientport);
        }
    }

    void Recver(int fd)
    {
        char buffer[1024];
        // 1.不一定是完整的报文
        // 2.读到部分报文 下次的Recver()函数中buffer是局部变量 
        // A报文如果发两次过来 也无法拼接成完整报文
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "get a messge: " << buffer << std::endl;
            std::string echo_str = "server echo $ ";
            echo_str += buffer;
            write(fd, echo_str.c_str(), echo_str.size());
        }
        else if (n == 0)
        {
            lg(Info, "client quit, me too, close fd is : %d", fd);
            _epollerPtr->EpllerUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
        else
        {
            lg(Warning, "recv error: fd is : %d", fd);
            _epollerPtr->EpllerUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
    }

    void Dispatcher(struct epoll_event revs[], int num)
    {
        for (int i = 0; i < num; i++)
        {
            uint32_t events = revs[i].events;
            int fd = revs[i].data.fd;
            if (events & ET_EVENT_IN) // 读取事件就绪[连接事件/普通读取事件]
            {
                if (fd == _listenSocketPtr->getSocketFd())
                    Accepter();
                else // 普通读取事件就绪
                    Recver(fd);
            }
            // else if (events & EVENT_OUT){}
            // else{}
        }
    }

    void Start()
    {
        // 将listensock添加到epoll中 -> listensock和他关心的事件 添加到内核epoll模型中rb_tree
        _epollerPtr->EpllerUpdate(EPOLL_CTL_ADD, _listenSocketPtr->getSocketFd(), ET_EVENT_IN);
        struct epoll_event revs[num];
        for (;;)
        {
            int n = _epollerPtr->EpollerWait(revs, num);
            if (n > 0) // 有事件就绪
            {
                lg(Debug, "event happened, first event fd is : %d", revs[0].data.fd);
                Dispatcher(revs, n);
            }
            else if (n == 0)
                lg(Info, "time out ...");
            else
                lg(Error, "epll wait error");
        }
    }

    ~EpollServer()
    {
        _listenSocketPtr->CloseFd();
    }
};